﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using NHibernate;
using NHibernate.Criterion;
using ZLCMS.Data.Model;
using ZLCMS.Business.Util;
using ZLCMS.Business;
using System.Collections;
using NHibernate.Transform;
using DotNet.Common.NHibernateUtil;
using ZLCMS.Commands.User.Util;

namespace ZLCMS.Web.SystemManage
{
    public partial class Default : System.Web.UI.Page
    {
        //订单模块
        protected int UnConfirmed{get;set;}
        protected int UnPayed{get;set;}
        protected int UnSended{get;set;}
        protected int UnFinished { get; set; }

        //产品模块
        protected int SellingProduct{get;set;}
        protected int FewStorage{get;set;}
        protected int SellCount { get; set; }

        //会员模块
        protected int MemberCounter{get;set;}
        protected int TodayMemberCounter { get; set; }
        protected string _userAccount;

        //退货模块
        protected int OrderReturnsConfirmed { get; set; }
        protected int OrderReturnsProcess { get; set; }
        protected int OrderReturnsFinished { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountWithoutException();
            if (string.IsNullOrEmpty(_userAccount))
            {
                Response.Redirect("/SystemManage/Login/Login.aspx");
            }

            SimpleStatistic();
        }

        protected void SimpleStatistic()
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                string departmentCode = session.CreateSQLQuery("select dept_code from sys_user_info where user_account=:acc")
                            .SetParameter("acc", _userAccount).UniqueResult<string>();
                if (AuthUtil.CheckAuthorization("ORDER_MAN", "VIEW_ALL", _userAccount))
                {
                    UnConfirmed = Convert.ToInt32(session.CreateSQLQuery("select count(Id) from shop_order_info where is_confirmed='0' and is_cancelled='0'").UniqueResult());
                    UnPayed = Convert.ToInt32(session.CreateSQLQuery("select count(Id) from shop_order_info where pay_status='0' and is_cancelled='0' ").UniqueResult());
                    UnSended = Convert.ToInt32(session.CreateSQLQuery("select count(Id) from shop_order_info where shipping_status='0' and is_cancelled='0'").UniqueResult());
                    UnFinished = Convert.ToInt32(session.CreateSQLQuery("select count(Id) from shop_order_info where shipping_status='1' and is_finished='0'").UniqueResult());
                }
                else if (AuthUtil.CheckAuthorization("ORDER_MAN", "VIEW_OWNER", _userAccount))
                {
                    UnConfirmed = Convert.ToInt32(session.CreateSQLQuery("select count(Id) from shop_order_info where is_confirmed='0' and dept_code=:code and is_cancelled='0'")
                        .SetParameter("code", departmentCode)
                        .UniqueResult());
                    UnPayed = Convert.ToInt32(session.CreateSQLQuery("select count(Id) from shop_order_info where pay_status='0'  and dept_code=:code and is_cancelled='0'")
                        .SetParameter("code", departmentCode)
                        .UniqueResult());
                    UnSended = Convert.ToInt32(session.CreateSQLQuery("select count(Id) from shop_order_info where shipping_status='0'  and dept_code=:code and is_cancelled='0'")
                        .SetParameter("code", departmentCode)
                        .UniqueResult());
                    UnFinished = Convert.ToInt32(session.CreateSQLQuery("select count(Id) from shop_order_info where shipping_status='1' and is_finished='0'  and dept_code=:code and is_cancelled='0'")
                        .SetParameter("code", departmentCode)
                        .UniqueResult());
                }
                if (AuthUtil.CheckAuthorization("PRODUCT_MAN", "VIEW_ALL", _userAccount))
                {
                    SellingProduct = Convert.ToInt32(session.CreateSQLQuery("select count(Id) from shop_product_info where status='1'").UniqueResult());
                    FewStorage = Convert.ToInt32(session.CreateSQLQuery("select count(recid) from shop_sku_product where storage>=0 and storage<=:num and status='1'")
                        .SetParameter("num", int.Parse(ParamKit.GetValue("SystemConfig", "StorageAlarm", "100")))
                        .UniqueResult());

                    SellCount = Convert.ToInt32(session.CreateSQLQuery("select sum(SALES_AMOUNT) from shop_product_sales_sum where DATE>=:d and DEPT_CODE='0000'")
                        .SetParameter("d", new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1))
                        .UniqueResult());
                }
                else if (AuthUtil.CheckAuthorization("PRODUCT_MAN", "VIEW_OWNER", _userAccount))
                {
                    SellingProduct = Convert.ToInt32(session.CreateSQLQuery("select count(Id) from shop_product_info where status='1' and dept_code=:code")
                            .SetParameter("code", departmentCode)
                            .UniqueResult());
                    FewStorage = Convert.ToInt32(session.CreateSQLQuery("select count(s.recid) from shop_sku_product s left join shop_product_info p on s.product_no=p.product_no where s.storage>=0 and  s.storage<=:num and p.dept_code=:code and s.status='1'")
                         .SetParameter("code", departmentCode)
                         .SetParameter("num", int.Parse(ParamKit.GetValue("SystemConfig", "StorageAlarm", "100")))
                         .UniqueResult());

                    SellCount = Convert.ToInt32(session.CreateSQLQuery("select sum(SALES_AMOUNT) from shop_product_sales_sum where DATE>=:d and DEPT_CODE=:code")
                        .SetParameter("d", new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1))
                        .SetParameter("code", departmentCode)
                        .UniqueResult());
                }

                if (AuthUtil.CheckAuthorization("MEMBER_MAN", "VIEW_ALL", _userAccount))
                {
                    MemberCounter = Convert.ToInt32(session.CreateSQLQuery("select count(Id) from member_info where status='1'").UniqueResult());
                    TodayMemberCounter = Convert.ToInt32(session.CreateSQLQuery("select count(Id) from member_info where date(add_date) = curdate() ").UniqueResult());
                }
                else if (AuthUtil.CheckAuthorization("MEMBER_MAN", "VIEW_OWNER", _userAccount))
                {
                    MemberCounter = Convert.ToInt32(session.CreateSQLQuery("select count(Id) from member_info where status='1' and dept_code=:code")
                             .SetParameter("code", departmentCode).UniqueResult());
                    TodayMemberCounter = Convert.ToInt32(session.CreateSQLQuery("select count(Id) from member_info where date(add_date) = curdate() and dept_code=:code")
                         .SetParameter("code", departmentCode).UniqueResult());
                }

                if (AuthUtil.CheckAuthorization("ORDER_RETURN_MAN", "VIEW_ALL", _userAccount))
                {
                    OrderReturnsConfirmed = Convert.ToInt32(session.CreateSQLQuery("select count(RecId) from shop_order_returns where confirm_status='0'and CANCEL_STATUS='0'").UniqueResult());
                    OrderReturnsFinished = Convert.ToInt32(session.CreateSQLQuery("select count(RecId) from shop_order_returns where finish_status='0' and CANCEL_STATUS='0' and process_status='1' ").UniqueResult());
                    OrderReturnsProcess = Convert.ToInt32(session.CreateSQLQuery("select count(RecId) from shop_order_returns where process_status='0' and CANCEL_STATUS='0' and confirm_status='1' ").UniqueResult());
                }
                else if (AuthUtil.CheckAuthorization("ORDER_RETURN_MAN", "VIEW_OWNER", _userAccount))
                {
                    OrderReturnsConfirmed = Convert.ToInt32(session.CreateSQLQuery("select count(RecId) from shop_order_returns where confirm_status='0'and CANCEL_STATUS='0'and dept_code=:code")
                            .SetParameter("code", departmentCode).UniqueResult());
                    OrderReturnsFinished = Convert.ToInt32(session.CreateSQLQuery("select count(RecId) from shop_order_returns where finish_status='0' and CANCEL_STATUS='0' and process_status='1' and dept_code=:code")
                        .SetParameter("code", departmentCode).UniqueResult());
                    OrderReturnsProcess = Convert.ToInt32(session.CreateSQLQuery("select count(RecId) from shop_order_returns where process_status='0' and CANCEL_STATUS='0' and confirm_status='1' and dept_code=:code")
                        .SetParameter("code", departmentCode).UniqueResult());
                }
            }
        }

        public String GetMenuString()
        {
            return MakeMenu(UserKit.GetUserAccountWithoutException());
            //不使用权限管理
            //return MakeMenu_WithoutRole("ADMIN");
        }

        protected string MakeMenu_WithoutRole(string role)
        {
            StringBuilder menuBuilder = new StringBuilder();
            SysMenuInfo menuRoot;

            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                // 获取该角色下菜单的根节点
                menuRoot = session.CreateCriteria<SysMenuInfo>().Add(Expression.Eq("Param1", role)).Add(Expression.Eq("IsShow", "1")).Add(Expression.Eq("Preid", -1)).UniqueResult<SysMenuInfo>();

                if (menuRoot == null)
                {
                    // 没有指定或不存在，则默认管理员权限
                    menuRoot = session.CreateCriteria<SysMenuInfo>().Add(Expression.Eq("Param1", "ADMIN")).Add(Expression.Eq("IsShow", "1")).Add(Expression.Eq("Preid", -1)).UniqueResult<SysMenuInfo>();

                    // 没有ADMIN，一般为配置错误
                    if (menuRoot == null)
                    {
                        return null;
                    }
                }

                IList<SysMenuInfo> list = session.CreateCriteria<SysMenuInfo>().Add(Expression.Eq("Preid", menuRoot.Id)).Add(Expression.Eq("Param1", role)).Add(Expression.Eq("IsShow", "1")).AddOrder(Order.Asc("Menuorder")).List<SysMenuInfo>();

                foreach (SysMenuInfo menu in list)
                {
                    menuBuilder.Append("<div class=\"accordionHeader\">");
                    menuBuilder.Append("<h2><span>Folder</span>" + menu.Title + "</h2>");
                    menuBuilder.Append("</div>");
                    menuBuilder.Append("<div class=\"accordionContent\">");
                    menuBuilder.Append("<ul class=\"tree treeFolder\">\n");
                    MakeSubMenu_WithoutRole(menu.Id, role, ref menuBuilder);
                    menuBuilder.Append("</ul></div>\n");
                }
            }

            return menuBuilder.ToString();
        }

        protected void MakeSubMenu_WithoutRole(int pid, string role, ref StringBuilder menuBuilder)
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                IList<SysMenuInfo> list = session.CreateCriteria<SysMenuInfo>().Add(Expression.Eq("Preid", pid)).Add(Expression.Eq("Param1", role)).Add(Expression.Eq("IsShow", "1")).AddOrder(Order.Asc("Menuorder")).List<SysMenuInfo>();

                foreach (SysMenuInfo menu in list)
                {
                    //sub sub ... folder
                    if (menu.Menuurl == "#")
                    {
                        menuBuilder.Append("<li><a href=\"javascript:void(0)\">");
                        menuBuilder.Append(menu.Title);
                        menuBuilder.Append("</a><ul>\n");
                        MakeSubMenu_WithoutRole(menu.Id, role, ref menuBuilder);
                        menuBuilder.Append("</ul></li>\n");
                    }
                    else //url
                    {
                        menuBuilder.Append("<li><a href=\"");
                        //menuBuilder.Append(ResolveUrl(menu.Menuurl));
                        String url = menu.Menuurl;
                        if (url.IndexOf("?") == -1)
                        {
                            url = url + "?tabtitle=" + Server.UrlEncode(menu.Title) + "&tabid=" + menu.Id;
                            //menuBuilder.Append("?tabtitle='" + Server.UrlEncode(menu.Title) + "'" + "&tabid=" + menu.Recid);
                        }
                        else
                        {
                            url = url + "&tabtitle=" + Server.UrlEncode(menu.Title) + "&tabid=" + menu.Id;
                            //menuBuilder.Append("&tabid=" + menu.Recid + "&tabtitle='" + Server.UrlEncode(menu.Title) + "'");
                        }
                        menuBuilder.Append(Server.UrlPathEncode(url));
                        menuBuilder.Append("\" target=\"navTab\" rel=\"" + menu.Id + "\">" + menu.Title + "</a></li>\n");
                        MakeSubMenu_WithoutRole(menu.Id, role, ref menuBuilder);
                    }
                }
            }
        }
        IList<IDictionary> menuList;

        protected string MakeMenu(string acc)
        {
            StringBuilder menuBuilder = new StringBuilder();
            IDictionary menuRoot;

            // 获取该角色下菜单的根节点
            //menuRoot = new AccessorFactory().GetMenuInfoAccessor().GetUniqueByCriteria(Restrictions.Eq("Param1", role), Restrictions.Eq("Preid", -1));
            string sql = @"select distinct `r`.`USER_CODE` AS `USER_CODE`,`sys_menu_info`.`RECID` AS `RECID`,`sys_menu_info`.`TITLE` AS `TITLE`,`sys_menu_info`.`HOTKEY` AS `HOTKEY`,`sys_menu_info`.`MENUURL` AS `MENUURL`,
`sys_menu_info`.`MENUORDER` AS `MENUORDER`,`sys_menu_info`.`MENULEVEL` AS `MENULEVEL`,`sys_menu_info`.`PREID` AS `PREID`,
`sys_menu_info`.`PARAM1` AS `PARAM1`,`sys_menu_info`.`PARAM2` AS `PARAM2`,`sys_menu_info`.`PARAM3` AS `PARAM3` 
from (`sys_menu_info` join `view_user_right` `r` on(((`sys_menu_info`.`RECID` = `r`.`RIGHT_CODE`) and (`r`.`GROUP_CODE` = _utf8'Menu') and (`sys_menu_info`.`IS_SHOW` = '1'))))";
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                menuRoot = session.CreateSQLQuery(sql + " where USER_CODE=:acc and PREID =-1 ")
                    .SetParameter("acc", acc)
                    .SetResultTransformer(Transformers.AliasToEntityMap).UniqueResult<IDictionary>();

                menuList = session.CreateSQLQuery(sql + " where USER_CODE=:acc order by `sys_menu_info`.`MENUORDER`")
                    .SetParameter("acc", acc).SetResultTransformer(Transformers.AliasToEntityMap).List<IDictionary>();

                if (menuRoot == null)
                {
                    // 没有指定或不存在，则默认管理员权限
                    //menuRoot = new AccessorFactory().GetMenuInfoAccessor().GetUniqueByCriteria(Restrictions.Eq("Param1", "ADMIN"), Restrictions.Eq("Preid", -1));

                    // 没有ADMIN，一般为配置错误
                    if (menuRoot == null)
                    {
                        return null;
                    }
                }

                //获取该角色根节点下的菜单
                //ICriteria crt = _menuAcc.CreateCriteria().Add(Expression.Eq("Preid", menuRoot["Recid"])).Add(Expression.Eq("Param1", role)).AddOrder(Order.Asc("Menuorder"));
                IList<IDictionary> list = session.CreateSQLQuery(sql + " where USER_CODE =:acc and PREID = " + menuRoot["RECID"] + " order by `sys_menu_info`.`MENUORDER` ")
                    .SetParameter("acc", acc)
                    .SetResultTransformer(Transformers.AliasToEntityMap).List<IDictionary>();
                foreach (IDictionary menu in list)
                {
                    menuBuilder.Append("<div class=\"accordionHeader\">");
                    menuBuilder.Append("<h2><span " + menu["PARAM3"] + ">Folder</span>" + menu["TITLE"] + "</h2>");
                    menuBuilder.Append("</div>");
                    menuBuilder.Append("<div class=\"accordionContent\">");
                    menuBuilder.Append("<ul class=\"tree treeFolder\">\n");
                    MakeSubMenu((int)menu["RECID"], acc, ref menuBuilder);
                    menuBuilder.Append("</ul></div>\n");
                }
            }

            return menuBuilder.ToString();
        }

        /// <summary>
        /// 获取指定角色在指定节点下的菜单信息
        /// </summary>
        /// <param name="pid">指定节点</param>
        /// <param name="role">指定角色</param>
        /// <param name="menuBuilder">返回菜单信息</param>
        protected void MakeSubMenu(int pid, string role, ref StringBuilder menuBuilder)
        {
            using (ISession session = SessionFactoryHelper.CreateSession())
            {
                //ICriteria crt = _menuAcc.CreateCriteria().Add(Expression.Eq("Preid", pid)).Add(Expression.Eq("Param1", role)).AddOrder(Order.Asc("Menuorder"));
                IList<IDictionary> list = new List<IDictionary>();
                foreach (var item in menuList)
                {
                    if (item["USER_CODE"].ToString() == role && Convert.ToInt32(item["PREID"]) == pid)
                    {
                        list.Add(item);
                    }
                }

                foreach (IDictionary menu in list)
                {
                    //sub sub ... folder
                    if ((string)menu["MENUURL"] == "#")
                    {
                        menuBuilder.Append("<li><a href=\"javascript:void(0)\">");
                        menuBuilder.Append(menu["TITLE"]);
                        menuBuilder.Append("</a><ul>\n");
                        MakeSubMenu((int)menu["RECID"], role, ref menuBuilder);
                        menuBuilder.Append("</ul></li>\n");
                    }
                    else //url
                    {
                        menuBuilder.Append("<li><a href=\"");
                        //menuBuilder.Append(ResolveUrl(menu.Menuurl));
                        String url = (string)menu["MENUURL"];
                        if (url.IndexOf("?") == -1)
                        {
                            url = url + "?tabtitle=" + Server.UrlEncode((string)menu["TITLE"]) + "&tabid=" + menu["RECID"];
                            //menuBuilder.Append("?tabtitle='" + Server.UrlEncode(menu.Title) + "'" + "&tabid=" + menu.Recid);
                        }
                        else
                        {
                            url = url + "&tabtitle=" + Server.UrlEncode((string)menu["TITLE"]) + "&tabid=" + menu["RECID"];
                            //menuBuilder.Append("&tabid=" + menu.Recid + "&tabtitle='" + Server.UrlEncode(menu.Title) + "'");
                        }
                        menuBuilder.Append(Server.UrlPathEncode(url));
                        menuBuilder.AppendFormat("\" target=\"navTab\" {0} rel=\"" + menu["RECID"] + "\">" + menu["TITLE"] + "</a></li>\n", "iframe" == menu["PARAM2"] as string ? "external=\"true\"" : "");

                        MakeSubMenu((int)menu["RECID"], role, ref menuBuilder);
                    }
                }
            }
        }
    }
}
